package cn.wit.summit.chwan.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.AdPosition;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.dto.PersonHomeData;
import cn.wit.summit.chwan.models.dto.PersonHomeDataUrl;
import cn.wit.summit.chwan.models.dto.SurplusNumberBean;
import cn.wit.summit.chwan.models.response.GetGameDetailShareDataResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.MYFollowGamsActivity;
import cn.wit.summit.chwan.ui.activity.MainActivity;
import cn.wit.summit.chwan.ui.activity.MainLoginActivity;
import cn.wit.summit.chwan.ui.activity.NoticeActivity;
import cn.wit.summit.chwan.ui.activity.SettingActivity;
import cn.wit.summit.chwan.ui.activity.UpdateActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.DateUtils;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.RedEnvelopeUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.MyBadgeView;
import cn.wit.summit.chwan.widgets.ShareBottomDialog;
import q.rorbin.badgeview.Badge;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/4/11.
 */

public class PersonalV2Fragment extends BaseFragment {
    private String TAG = "PersonalV2Fragment";

    @Bind(R.id.personalTopBgIv)
    SimpleDraweeView personalTopBgIv;
    @Bind(R.id.personalTopUnloginLl)
    LinearLayout personalTopUnloginLl;
    @Bind(R.id.personalTopLoginLl)
    LinearLayout personalTopLoginLl;
    @Bind(R.id.personalTopLoginIconIv)
    SimpleDraweeView personalTopLoginIconIv;
    @Bind(R.id.personalTopLoginNameTx)
    TextView personalTopLoginNameTx;
    @Bind(R.id.personalTopMoneyTx)
    TextView personalTopMoneyTx;
    @Bind(R.id.personalTopMoneyRl)
    RelativeLayout personalTopMoneyRl;
    @Bind(R.id.personalTopRl)
    RelativeLayout personalTopRl;
    @Bind(R.id.personalTopSettingIv)
    ImageView personalTopSettingIv;
    @Bind(R.id.iv1)
    ImageView iv1;
    @Bind(R.id.personalMessageRl)
    RelativeLayout personalMessageRl;
    @Bind(R.id.iv2)
    ImageView iv2;
    @Bind(R.id.personalGameRl)
    RelativeLayout personalGameRl;
    @Bind(R.id.iv4)
    ImageView iv4;
    @Bind(R.id.personalUpRl)
    RelativeLayout personalUpRl;

    private Context context;
    private Badge messagebadge;
    private Badge updateImgBadge;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    private Uri loginUri;
    private Uri unLoginUri;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_personal_v2, container, false);
        ButterKnife.bind(this, view);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        context = getContext();

        loginUri = Uri.parse("res:///" + R.mipmap.personal_top_bg_login);
        unLoginUri = Uri.parse("res:///" + R.mipmap.personal_top_bg_unlogin);

        getUpdateInfo();
        updateMessage();

        long ennerTime = PreferenceUtil.getLongPreferences(context, "clickTodayGetEnergy");
//        if (ennerTime == 0 || !DateUtils.isToday(ennerTime)) {
//            energybadge = new MyBadgeView(getContext())
//                    .bindTarget(ennergytext)
//                    .setBadgeNumber(-1)
//
//                    .setBadgePadding(getResources().getDimensionPixelSize(R.dimen.wdp8), false)
//
//                    .setBadgeBackground(getResources().getDrawable(R.mipmap.notice_round))
//                    .setBadgeTextSize(getResources().getDimensionPixelSize(R.dimen.wdp18), false)
//                    .setBadgeGravity(Gravity.START | Gravity.TOP)
//                    .setBadgeTextColor(Color.WHITE)
//                    .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
//                        @Override
//                        public void onDragStateChanged(int dragState, Badge badge, View targetView) {
//                            if (dragState == 4)
//                                badge.hide(false);
//                        }
//                    });
//
//        }

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
        getUserinfo();
        getNewRedEnvelope();
        getUpdateInfo();
        getSurplusNumber();
    }

    private void initView() {
        LogUtils.e(TAG + " initView()");
        AccountBean accountBean = AccountUtil.getInstance().getAccountData();
        if (accountBean == null || accountBean.getUid() == 0) {
            personalTopUnloginLl.setVisibility(View.VISIBLE);
            personalTopLoginLl.setVisibility(View.GONE);
//            personalTopSettingIv.setVisibility(View.GONE);
            personalTopLoginIconIv.setImageURI("");
            personalTopMoneyTx.setText("0元");
            personalTopBgIv.setImageURI(unLoginUri);
        } else {
            personalTopUnloginLl.setVisibility(View.GONE);
            personalTopLoginLl.setVisibility(View.VISIBLE);
//            personalTopSettingIv.setVisibility(View.VISIBLE);
            personalTopLoginIconIv.setImageURI(Uri.parse(accountBean.getAvatar()));
            personalTopLoginNameTx.setText(accountBean.getNickname());
            DecimalFormat df = new DecimalFormat("0.00");
            personalTopMoneyTx.setText(df.format(accountBean.getTodayIncome() / 100f)+"元");
            personalTopBgIv.setImageURI(loginUri);
        }

    }

    //广告位
//    private void getPersonhomeData() {
//        if (NetWorkUtils.isNetworkConnected(context)) {
//            try {
//                api.getPersonData("").enqueue(new MyCallback<ResponseBase<PersonHomeData>>() {
//                    @Override
//                    public void onSuccess(ResponseBase<PersonHomeData> model) {
//                        final PersonHomeData data = model.getData_info();
//                        if (data != null) {
//                            if (data.getJump_ad_switch() == 1) {
//                                bannerAd.setImageURI(data.getJump_cover_big_pic());
//                                bannerAd.setOnClickListener(new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View v) {
//                                        IntentUtil.getInstance().intentTo(getActivity(), data.getJump_info());
//                                        StatFactory.getInstance().sendClickAdvertSpacePage(getContext(), AdPosition.getModeByEnum(8)
//                                                , AdPosition.getNameByEnum(8), "", "", 1);
//                                    }
//                                });
//                                bannerAd.setVisibility(View.VISIBLE);
//
//                            } else {
//                                bannerAd.setVisibility(View.GONE);
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(int code, String msg) {
//
//                    }
//                });
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    private void getUserinfo() {
        if (NetWorkUtils.isNetworkConnected(context)) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    apiLogin.checkToken(uid, token).enqueue(new MyCallback<ResponseBase<PersonHomeDataUrl>>() {
                        @Override
                        public void onSuccess(ResponseBase<PersonHomeDataUrl> model) {
                            PersonHomeDataUrl data = model.getData_info();
                            if (data != null) {
                                data.setToken(AccountUtil.getInstance().getToken());
                                AccountUtil.getInstance().saveAccountData(data);
                                initView();

                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(getActivity());
                                initView();
                            } else {
                                ToastUtils.getInstance(context).showToastSystem(msg);
                            }
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void getNewRedEnvelope() {
//        SharedPreferences s = MyApplication.getMyApplication().getRedps();
//        if (s.getBoolean("isclose", false) == false) {
//            Log.e("TAG", "PerOnResume");
//            RedEnvelopeUtils.ShowRedEnvelope(getActivity());
//        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
//            getPersonhomeData();
            getUserinfo();
            getNewRedEnvelope();
            getUpdateInfo();
            getSurplusNumber();
        }
    }

    private void getUpdateInfo() {
        if (NetWorkUtils.isNetworkConnected(context)) {
            try {
                final List<DownLoadTaskTable> downLoadTaskTables = DownloadTaskManager.getInstance().findAllGame();
                StringBuffer buffer = new StringBuffer();
                for (DownLoadTaskTable taskTable : downLoadTaskTables) {
                    buffer.append("," + taskTable.getPackageName());
                    APKUtils.APKInfo apkInfo = APKUtils.getInstance(context).getInstallAPKInfo(context, taskTable.getPackageName());
                    if (apkInfo == null) continue;
                    buffer.append("|");
                    buffer.append(apkInfo.getVersionName() + "_" + apkInfo.getVersionCode());
                }
                String packagenames = buffer.toString();
                packagenames = packagenames.replaceFirst(",", "");

                api.getAllGameVersion(packagenames).enqueue(new MyCallback<ResponseBase<List<GameListBaseBean>>>() {
                    @Override
                    public void onSuccess(ResponseBase<List<GameListBaseBean>> model) {
                        List<GameListBaseBean> data = model.getData_info();
                        if (data.size() > 0) {
                            Iterator<GameListBaseBean> gaIterator = data.iterator();
                            int needUpdateNumber = 0;
                            while (gaIterator.hasNext()) {
                                try {

                                    GameListBaseBean gameListBaseBean = gaIterator.next();
                                    APKUtils.APKInfo apkInfo = APKUtils.getInstance(context).getInstallAPKInfo(context, gameListBaseBean.getGame_package_name());
                                    if (apkInfo != null && apkInfo.getVersionCode() < gameListBaseBean.getGame_ver()) {
                                        DownLoadTaskTable taskTable = DownloadTaskManager.getInstance().findByGameId(gameListBaseBean.getGame_id());
                                        if (taskTable != null && taskTable.getNotUpdateVersion() == gameListBaseBean.getGame_ver()) {
                                            continue;
                                        }
                                        needUpdateNumber += 1;
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            if (needUpdateNumber > 0) {
                                if (updateImgBadge != null) {
                                    updateImgBadge.hide(false);
                                }
                                updateImgBadge = new MyBadgeView(getContext())
                                        .bindTarget(iv4)
                                        .setBadgeNumber(needUpdateNumber > 99 ? 99 : needUpdateNumber)
                                        .setBadgePadding(getResources().getDimensionPixelSize(R.dimen.wdp5), false)
                                        .setBadgeBackground(getResources().getDrawable(needUpdateNumber > 99 ? R.mipmap.notice_round_nore99 : R.mipmap.notice_round))
                                        .setBadgeTextSize(getResources().getDimensionPixelSize(R.dimen.wdp16), false)
                                        .setBadgeGravity(Gravity.END | Gravity.TOP)
                                        .setBadgeTextColor(Color.WHITE)
                                        .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                                            @Override
                                            public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                                                if (dragState == 4)
                                                    badge.hide(false);
                                            }
                                        });
                            }
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }
    }

    private void getSurplusNumber() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                int uid = AccountUtil.getInstance().getUid();
                String token = AccountUtil.getInstance().getToken();
                api.getSurplusNumber(uid, token).enqueue(new MyCallback<ResponseBase<SurplusNumberBean>>() {
                    @Override
                    public void onSuccess(ResponseBase<SurplusNumberBean> model) {
                        SurplusNumberBean data = model.getData_info();
                        if (data != null) {
                            try {
                                updateMessage();
                                if (getActivity()!=null) {
                                    MainActivity activity = (MainActivity) getActivity();
                                    activity.surplusNumberBean = data;
                                }
                            } catch (Exception e) {

                            }
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void updateMessage() {
        MainActivity activity = (MainActivity) getActivity();

        if (activity.surplusNumberBean != null) {

            int showNumber = activity.surplusNumberBean.getNotice_surplus_number() + activity.surplusNumberBean.getReplay_surplus_number();
            if (showNumber > 0 || activity.surplusNumberBean.getPraise_surplus_number() > 0) {
                if (showNumber == 0) {
                    showNumber = -1;
                }
                if (messagebadge==null) {
                    messagebadge = new MyBadgeView(getContext())
                            .bindTarget(iv1)
                            .setBadgeNumber(showNumber > 99 ? 99 : showNumber)
                            .setBadgePadding(getResources().getDimensionPixelSize(R.dimen.wdp5), false)
                            .setBadgeBackground(getResources().getDrawable(showNumber > 99 ? R.mipmap.notice_round_nore99 : R.mipmap.notice_round))
                            .setBadgeTextSize(getResources().getDimensionPixelSize(R.dimen.wdp16), false)
                            .setBadgeGravity(Gravity.END | Gravity.TOP)
                            .setBadgeTextColor(Color.WHITE)
                            .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                                @Override
                                public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                                    if (dragState == 4)
                                        badge.hide(false);
                                }
                            });
                } else {
                    messagebadge.setBadgeNumber(showNumber);
                }
            } else {
                if (messagebadge != null)
                    messagebadge.hide(false);
            }
        } else {
            if (messagebadge != null)
                messagebadge.hide(false);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.personalTopLoginBt, R.id.personalTopMoneyRl, R.id.personalMessageRl, R.id.personalGameRl, R.id.personalUpRl
            , R.id.personalBackMessageRl, R.id.personalUpgradeRl, R.id.personalTopSettingIv, R.id.personalSetRl, R.id.personalShareRl})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.personalShareRl:
                if (AccountUtil.getInstance().getUidNotToLogin(getActivity()) == 0) return;
                getShareData();
                break;
            case R.id.personalTopLoginBt:
                IntentUtil.getInstance().goLoginActivity(getActivity());
                break;
            case R.id.personalTopMoneyRl:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_wallet_url_v2());
                break;
            case R.id.personalMessageRl:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                if (messagebadge != null)
                    messagebadge.hide(false);
                intent = new Intent(this.getContext(), NoticeActivity.class);
                MainActivity activity = (MainActivity) getActivity();
                if (activity.surplusNumberBean != null) {
                    SurplusNumberBean bean = new SurplusNumberBean();
                    bean.setNotice_surplus_number(activity.surplusNumberBean.getNotice_surplus_number());
                    bean.setPraise_surplus_number(activity.surplusNumberBean.getPraise_surplus_number());
                    bean.setReplay_surplus_number(activity.surplusNumberBean.getReplay_surplus_number());
                    intent.putExtra("numberData", bean);
                    if (activity.surplusNumberBean.getNotice_surplus_number() > 0) {
                        activity.surplusNumberBean.setNotice_surplus_number(0);
                    } else {
                        activity.surplusNumberBean.setReplay_surplus_number(0);
                    }
                }
                startActivity(intent);
                break;
            case R.id.personalGameRl:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                startActivity(new Intent(context, MYFollowGamsActivity.class));
                break;
            case R.id.personalUpRl:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_game_upload_url_v3());
                break;
            case R.id.personalUpgradeRl:
                if (updateImgBadge != null) {
                    updateImgBadge.hide(false);
                }
                intent = new Intent(this.getContext(), UpdateActivity.class);
                startActivity(intent);
                break;
            case R.id.personalBackMessageRl:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_feedback_url_v3());
                break;
            case R.id.personalTopSettingIv:
            case R.id.personalSetRl:
                if (MyApplication.accountBean == null) {
                    IntentUtil.getInstance().goLoginActivity(getActivity());
                } else {
                    if(MyApplication.accountBean.getToken()!=null){
                        startActivity(new Intent(getActivity(), SettingActivity.class));
                    }else{
                        ToastUtils.getInstance(getActivity()).showToastSystem("token为空");
                    }
                }
                break;
        }
    }

    private void getShareData() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                int uid = AccountUtil.getInstance().getUid();
                String token = AccountUtil.getInstance().getToken();
                showLoading("获取分享数据中...");
                apiLogin.getShareDataPersonal(uid, token).enqueue(new MyCallback<ResponseBase<GetGameDetailShareDataResponse>>() {
                    @Override
                    public void onSuccess(ResponseBase<GetGameDetailShareDataResponse> model) {
                        GetGameDetailShareDataResponse response = model.getData_info();
                        cancelLoading();
                        if (response!=null && response.getRecord()!=null) {
                            String shareUrl = response.getRecord().getSharePicURL();
                            if (!StringUtils.isEmpty(shareUrl)) {
                                WindowManager windowManager = getActivity().getWindowManager();
                                Display display = windowManager.getDefaultDisplay();
                                new ShareBottomDialog(getActivity(), display.getWidth(), shareUrl, 1).show();
                            } else {
                                showToast("分享数据获取失败，请稍后再试！");
                            }
                        } else {
                            showToast("分享数据获取失败，请稍后再试！");
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        cancelLoading();
                        showToast(msg);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            showToast("网络出错，请稍后再试！");
        }
    }
}
